<?php

namespace app\controllers;

use app\actions\SiteMapAction;
use app\components\AppController;
use app\helpers\AppHelper;
use app\models\Book;
use app\models\Comment;
use app\models\Meta;
use app\models\Relationship;
use app\models\SearchHistory;
use Yii;
use yii\caching\TagDependency;
use yii\data\ActiveDataProvider;
use yii\db\Exception;
use yii\helpers\ArrayHelper;

class SiteController extends AppController {

    public function actionIndex() {
        $duration = 3600;
        $update_items = Book::find()->cache($duration)->limit(12)->orderBy('update_time desc, view_count desc')->asArray()->all();
        $new_items = Book::find()->cache($duration)->limit(12)->orderBy('create_time desc, view_count desc')->asArray()->all();
        $top_items = Book::find()->cache($duration)->limit(12)->orderBy('view_count desc')->asArray()->all();
        return $this->render(compact('new_items', 'update_items', 'top_items'));
    }

    public function actionUpdate() {
        $start_time = strtotime(date('Y-m-d'));
        $where = ['>', 'update_time', $start_time];
        $query = Book::find()->where($where)->asArray();
        $query->orderBy('update_time desc');
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => ['defaultPageSize' => 30],
        ]);
        return $this->render(compact('dataProvider'));
    }

    public function actionCategory() {
        $metas = Meta::find()->cache(3600)->where(['type' => Meta::TYPE_TAG])->asArray()->all();
        $tagList = ArrayHelper::map($metas, 'slug', 'slug');
        $tagMap = ArrayHelper::map($metas, 'slug', 'id');

        $params = [
            'is_finish' => $this->get('finish'),
            'letter' => $this->get('letter')
        ];

        $query = Book::find();
        $query->andFilterWhere($params);
        $t = $this->get('t');
        if ($t && isset($tagMap[$t])) {
            $meta_id = $tagMap[$t];
            $table = Relationship::tableName();
            $query->leftJoin("{$table} b", 'b.owner_id = id');
            $query->andWhere(['b.meta_id' => $meta_id]);
        }
        $wd = $this->get('wd');
        if ($wd) {
            $query->andFilterWhere(['like', 'title', $wd]);
            SearchHistory::saveHistory($wd);
        }

        $query->orderBy('view_count desc');
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => ['defaultPageSize' => 36],
        ]);
        return $this->render(compact('tagList', 'dataProvider'));
    }

    /**
     * @return array|bool|string
     * @throws Exception
     */
    public function actionMessage() {
        $model = new Comment();
        if (!$model->load($this->post())) {
            return $this->renderPartial('/message', compact('model'));
        }

        $model->type = Comment::TYPE_REPORT;
        $res = $model->save();
        $res['msg'] = '留言成功';
        return $res;
    }

    public function actions() {
        $actions = parent::actions();
        $actions['map'] = ['class' => SiteMapAction::class];
        return $actions;
    }

    public function actionTest() {
        $str = sprintf('%s-%s', Yii::$app->request->remoteIP, Yii::$app->request->userAgent);
        $str = substr(md5($str), 8, 8);
        echo substr(bin2hex($str), 0, 9);
    }
}
